﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JGSoft.U9CRTAPIEX.Public
{
    public static class LogManager
    {
        public static void WriteLog(string msg, string doctype)
        {
            try
            {
                string logFile = doctype;
                string filename = $"debug_{logFile}_" + DateTime.Now.ToString("yyyyMMdd") + ".Log";
                string path = $"{AppDomain.CurrentDomain.BaseDirectory}\\Logs";

                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                // Check if today's log file exists, if not, delete old logs
                if (!File.Exists($"{path}\\{filename}"))
                    DeleteOldLogs(path);

                System.IO.StreamWriter sw = File.AppendText($"{path}\\{filename}");
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + " " + msg);
                sw.Close();
            }
            catch
            { }
        }
        /// <summary>
        /// 删除60天以前的日志
        /// </summary>
        /// <param name="path"></param>
        public static void DeleteOldLogs(string path)
        {
            try
            {
                var files = Directory.GetFiles(path);
                files = files.Where(t=> Path.GetFileName(t).StartsWith("debug_")).ToArray();
                foreach (var file in files)
                {
                    FileInfo fi = new FileInfo(file);
                    if (fi.CreationTime < DateTime.Now.AddDays(-92))
                        fi.Delete();
                }
            }
            catch
            { }
        }
    }
}
